package hk.com.fgoproduction.getdroplets.BroadcastAndNoti

import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Icon
import android.os.Build
import hk.com.fgoproduction.getdroplets.Activity.MainActivity
import hk.com.fgoproduction.getdroplets.R

class NotiHandler(val ctx: Context) {

    private lateinit var notiMgr: NotificationManager
    private lateinit var builder: Notification.Builder

    private val NOTI_ID = 2000

    fun start() {
        initialize()
    }

    private fun initialize() {
        notiMgr = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        builder = Notification.Builder(ctx)

        //TODO to task page
        val onTouchPIntent = pIntentFactory(PendingIntent.FLAG_UPDATE_CURRENT, MainActivity::class.java)

        val cancelIntent = Intent(NotiReceiver.NOTI_TAG_IO)
        cancelIntent.putExtra("id", NotiReceiver.ACTION_CANCEL)
        val cancelPIntent = pIntentFactory(PendingIntent.FLAG_ONE_SHOT, cancelIntent)

        setBuilderLayout(builder)
        builder.setContentIntent(onTouchPIntent)
                .addAction(actionFactory("Cancel", cancelPIntent))

        notiMgr.notify(NOTI_ID, builder.build())
    }

    private fun actionFactory(title: String, intent: PendingIntent): Notification.Action {
        val builder: Notification.Action.Builder
        val icon: Icon

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            icon = Icon.createWithResource(ctx, 0)
            builder = Notification.Action.Builder(icon, title, intent);
        } else {
            builder = Notification.Action.Builder(0, title, intent);
        }

        return builder.build();
    }

    //TODO Progress bar!
    private fun setBuilderLayout(builder: Notification.Builder) {
        builder.setSmallIcon(R.drawable.notification_template_icon_bg)
                .setContentTitle(stringOfR(R.string.app_name))
                .setContentText("Testing")
                .setDefaults(Notification.DEFAULT_ALL)
                .setOngoing(true)
    }

    private fun <T> pIntentFactory(flag: Int, activity: Class<T>) : PendingIntent {
        return PendingIntent.getActivity(ctx, NOTI_ID, Intent(ctx, activity), flag)
    }

    private fun pIntentFactory(flag:Int, broadcastIntent: Intent) : PendingIntent {
        return PendingIntent.getBroadcast(ctx.applicationContext, NOTI_ID, broadcastIntent, flag)
    }

    private fun stringOfR(id: Int) : String {
        return ctx.resources.getString(id)
    }

}
